<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户卡片 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 用户输入的内容  params.query -->
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="params.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              @click="getUserList"
              slot="append"
              icon="el-icon-search"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addUser = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <!-- data	显示的数据 -->
      <el-table :data="users" border style="width: 100%">
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="qiehuan(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- 修改角色 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editUserById(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="fenpeijuese(scope.row.id, scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUser"
      width="50%"
      @close="restAddUser"
    >
      <el-form
        :model="addUserData"
        :rules="addUserRules"
        label-width="70px"
        ref="addUser"
        @click="addUseraxios"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserData.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserData.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUser = false">取 消</el-button>
        <el-button type="primary" @click="addUseraxios">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <!-- :visible.sync 显示隐藏 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form
        label-width="80px"
        ref="edidtForm"
        :model="editUserData"
        :rules="editUserRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserData.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserData.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUser">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      @close="roleId = ''"
      title="分配角色"
      :visible.sync="fenpei_dialogVisible"
      width="50%"
    >
      <div>当前用户:{{ fenpeijuese_shuju.username }}</div>
      <div>当前用户:{{ fenpeijuese_guanliyuan }}</div>
      <div>
        管理权限：
        <el-select v-model="roleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //自定义验证规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (!regEmail.test(value)) {
        return callback(new Error("邮箱格式不正确"));
      }
      callback();
    };
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (!regMobile.test(value)) {
        return callback(new Error("手机号格式不正确"));
      }
      callback();
    };

    return {
      params: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      users: [],
      total: 0,
      addUser: false,
      addUserData: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //  修改对话框---显示隐藏
      editDialogVisible: false,
      editUserData: {
        username: "",
        email: "",
        mobile: "",
        id: "",
      },
      editUserRules: {
        id: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 分配角色
      fenpei_dialogVisible: false,
      fenpeijuese_shuju: {},
      fenpeijuese_guanliyuan: "",
      //所有角色列表
      rolesList: [],
      //分配用户角色
      //角色id  roleId
      roleId: "",
      //用户id  userId
      userId: "",
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    //渲染数据
    async getUserList() {
      const { data: res } = await this.$axios.get("users", {
        params: this.params,
      });
      //   console.log(res.data);
      this.users = res.data.users;
      this.total = res.data.total;
    },
    //切换状态
    async qiehuan(res) {
      // console.log(res);
      const { data: res1 } = await this.$axios.put(
        `users/${res.id}/state/${res.mg_state}`
      );
      if (res1.meta.status != 200) {
        return this.$message.error("设置失败");
      }
      // console.log(res1);
      this.$message.success(res1.meta.msg);
    },
    //分页
    handleSizeChange(val) {
      this.params.pagesize = val;
      this.getUserList();
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.params.pagenum = val;
      this.getUserList();
      // console.log(`当前页: ${val}`);
    },
    //重置表单
    restAddUser() {
      //重置表单
      this.$refs.addUser.resetFields();
      //隐藏文本框
      this.addUser = false;
    },
    //校验
    addUseraxios() {
      //js校验
      this.$refs.addUser.validate(async (vaild) => {
        if (!vaild) {
          return this.$message.error("请输入合法的表单");
        }
        //发送
        const { data: res } = await this.$axios.post(
          "/users",
          this.addUserData
        );
        console.log(res);
        if (res.meta.status != 201) {
          return this.$message.error("创建失败");
        }
        this.$message.success(res.meta.msg);
        //关闭文本框
        this.restAddUser();
        //重新渲染
        this.getUserList();
      });
    },
    //删除用户
    async deleteUser(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(confirmResult);
      //取消删除
      if (confirmResult == "cancel") {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      }
      //确定删除
      //如果只有一条，删除完返回上一页
      if (this.users.length == 1) {
        this.params.pagenum--;
      }
      const { data: res } = await this.$axios.delete("/users/" + id);
      //删除失败
      if (status != 200) {
        this.$message.error("删除失败");
      }
      // console.log(res);
      this.$message.success("删除成功");
      //重新渲染
      this.getUserList();
    },
    //修改用户
    async editUserById(id) {
      // console.log(id);
      this.editDialogVisible = true;
      const { data: res } = await this.$axios.get("users/" + id);
      // console.log(res);
      this.editUserData = res.data;
      // console.log(this.editUserData);
    },
    //验证
    editUser() {
      const id = this.editUserData.id;
      // console.log(this.editUserData.id);
      //验证
      this.$refs.edidtForm.validate(async (vaild) => {
        if (!vaild) {
          return this.$message.error("请输入合法的表单");
        }
        const { data: res } = await this.$axios.put("users/" + id, {
          email: this.editUserData.email,
          mobile: this.editUserData.mobile,
        });
        // console.log(res);
        this.editUserData = res.data;
        // console.log(this.editUserData);
        this.getUserList();
        this.resetEditForm();
      });
    },
    //重置表单
    resetEditForm() {
      this.$refs.edidtForm.resetFields();
      this.editDialogVisible = false;
    },
    // 分配角色
    async fenpeijuese(id, role) {
      // console.log(role.role_name);
      // console.log(id);
      this.userId = id;
      this.fenpeijuese_guanliyuan = role.role_name;
      const { data: res } = await this.$axios.get("users/" + id);
      // console.log(res);
      this.fenpeijuese_shuju = res.data;

      const { data: res1 } = await this.$axios.get("roles");
      // console.log(res1);
      this.rolesList = res1.data;
      this.fenpei_dialogVisible = true;
    },
    //分配角色确定提交
    async setUserRoles() {
      // console.log(this.roleId);
      // console.log(this.userId);
      const { data: res } = await this.$axios.put(`users/${this.userId}/role`, {
        rid: this.roleId,
      });
      // console.log(res);
      if (res.meta.status != 200) {
        this.$message.error(res.meta.msg);
      }
      // console.log(res);
      this.$message.success(res.meta.msg);
      //重新渲染
      this.getUserList();
      this.fenpei_dialogVisible = false;
    },
  },
};
</script>

<style lang="less">
.el-breadcrumb {
  font-size: 12px;
}
.el-table {
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>